package xhg.com.resell.base.activitybase;

import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import xhg.com.resell.R;
import xhg.com.resell.utils.ActivityManager;

/**
 * @author lew1210
 * baseActivity
 */
public abstract class BaseActivity<V extends BaseView, P extends BasePresenter<V>>
        extends AppCompatActivity {

    protected P mPresenter;
    private LoadingDialog loadingDialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().add(this);
        setContentView(getLayoutId());



        mPresenter = createPresenter();
        initToolBar();
        attachView();
        bindView();
        bindEvent();
        initData();
    }

    private  void initToolBar() {
        ImageView ivBack = findViewById(R.id.iv_back);
        if (ivBack != null) {
            ivBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        TextView title = findViewById(R.id.tv_bar_title);
        if (title != null) {
            String txt = setTitle();
            if (!TextUtils.isEmpty(txt)) {
                title.setText(txt);
            }
        }


    }

    /**
     * 得到布局id
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 控件初始化
     */
    protected abstract void bindView();

    /**
     * 生成P
     */
    protected abstract P createPresenter();

    /**
     * 数据初始化
     */
    protected abstract void initData();

    /**
     * 监听事件得一些绑定
     */
    protected abstract void bindEvent();

    /**
     * 设置标题
     */
    protected abstract String setTitle();



    /**
     * p 与 v 绑定
     */
    private void attachView() {
        if (mPresenter != null) {
            if (this instanceof BaseView) {
                mPresenter.attachView((V)this);
            }

        }
    }

    @Override
    protected void onDestroy() {
        ActivityManager.getInstance().remove(this);
        showLoading(false);
        if (mPresenter != null) {
            //接触绑定
            mPresenter.detchView();
        }
        super.onDestroy();
    }

    public void showLoading(boolean isShow) {
        if (isShow) {
            if (loadingDialog == null) {
                loadingDialog = new LoadingDialog(this);
            }
            loadingDialog.show();
        } else {
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        }
    }

    /**
     * 点击空白处让键盘消失
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
                View v = getCurrentFocus();
                if (isShouldHideInput(v, ev)) {
                    if (v != null) {
                        hideSoftInput(v.getWindowToken());
                    }
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if ( (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, 0);
            }
        }
    }

}
